<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
// load base class if needed
require_once( APPPATH . 'controllers/base/OperatorBase.php' );

class distribusi extends ApplicationBase {

    // constructor
    public function __construct() {
        parent::__construct();
        // load model
        $this->load->model('m_pengadaan');
        $this->load->model('m_bagian');
        $this->load->model('m_lokasi');
        $this->load->model('m_barang');
        $this->load->model('m_group_barang');
        $this->load->model('m_kategoribarang');
        $this->load->model('m_jenisbarang');
        $this->load->model('m_merk');
        $this->load->model('m_pengajuan_barang');

        $this->load->model('m_operator_mini');
        // load library
        $this->load->library('tnotification');
        $this->load->library('pagination');
        $this->load->library('datetimemanipulation'); 
        $this->load->library('phpexcel');

        // load helpers
        $this->smarty->load_javascript("resource/js/jquery/jquery-ui-1.9.2.custom.min.js");
        $this->smarty->load_style("jquery.ui/redmond/jquery-ui-1.8.13.custom.css");
        //select 2
        $this->smarty->load_javascript("resource/js/lightbox/lightbox-2.6.min.js");
        $this->smarty->load_style("select2/select2.css");
    }

    // welcome administrator
    public function index() {
        $this->_set_page_rule("R");

        // set template content
        $this->smarty->assign("template_content", "inventarisasi/distribusi/list.html");

        // notification
        $this->tnotification->display_notification();
        $this->tnotification->display_last_field();

        // output
        parent::display();
    }
    
    public function beritacara_proccess() { 
        //cek data
        $this->tnotification->set_rules('pengadaan_id', 'Nomor Pengadaan', 'trim|required'); 
        
        //proses
        if ($this->tnotification->run() !== FALSE) { 
            if (!empty($_FILES['pengadaan_att_dist']['tmp_name'])) {
                
                $nomor_berita_acara = $this->input->post('pengadaan_ba_dist');
                $nomor_berita_acara = str_replace(".", "",$nomor_berita_acara);
                $nomor_berita_acara = str_replace("/", "_",$nomor_berita_acara);
                // load
                $this->load->library('tupload');
                // delete
                $filename = $nomor_berita_acara; 
                $filepath = 'resource/userfile/pengadaan/' . $filename; 
                // upload config
                $config['upload_path'] = 'resource/userfile/pengadaan/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '1000';
                $config['max_width'] = '1024';
                $config['max_height'] = '800';
                $config['file_name'] = $filename; 
                $this->tupload->initialize($config); 
                if(!$this->tupload->do_upload_image('pengadaan_att_dist')){
                    // jika gagal (kembalikan pesan)
                    $this->tnotification->set_error_message($this->tupload->display_errors());
                    $this->tnotification->sent_notification("error", "File gagal diupload");
                    $filename = null;
                } else {
                    $data_upload = $this->tupload->data();
                    $filename = $data_upload['file_name']; 
                    //hapus file lama
                    $result_info = $this->m_pengadaan->get_pengadaan_by_pengadaan_id($this->input->post('pengadaan_id'));
                    if($result_info['pengadaan_att_dist']!=''){
                        unlink('resource/userfile/pengadaan/'.$result_info['pengadaan_att_dist']);
                    } 
                    $this->tnotification->sent_notification("success", "File berhasil diupload");
                }
            }
            $params = array(
                'pengadaan_ba_dist'     => $this->input->post('pengadaan_ba_dist'),
                'pengadaan_tgl_dist'    => $this->input->post('pengadaan_tgl_dist'),
                'pengadaan_att_dist'    => $filename,
                'pengadaan_id'          => $this->input->post('pengadaan_id')
            ); 
            
            $this->m_pengadaan->set_update_serah_terima($params);
        } else {
            // default error
            $this->tnotification->sent_notification("error", "Data gagal disimpan");
        } 
        
        redirect('inventarisasi/pengadaan/distribusi/' . $this->input->post('pengadaan_id'));
    }
    
    public function distribusi_proccess() { 
        //cek data
        $this->tnotification->set_rules('pengadaan_id', 'Nomor Pengadaan', 'trim|required'); 
        
        //proses
        if ($this->tnotification->run() !== FALSE) { 
            $barang_id              = $this->input->post('barang_id');
            $barang_nama            = $this->input->post('barang_nama');
            $barang_umurekonomis    = $this->input->post('barang_umurekonomis');
            $barang_tglbeli         = $this->input->post('barang_tglbeli');
            $barang_harga_beli      = $this->input->post('barang_harga_beli');
            $ruang_cd               = $this->input->post('ruang_cd');
            
            foreach ($barang_id as $key => $value) {
                $params = array(
                    'barang_nama'           => $barang_nama[$key],
                    'barang_umurekonomis'   => $barang_umurekonomis[$key],
                    'barang_tglbeli'        => $barang_tglbeli[$key],
                    'barang_harga_beli'     => str_replace(".","", $barang_harga_beli[$key]),
                    'barang_nilai_buku'     => str_replace(".","", $barang_harga_beli[$key]),
                    'ruang_cd'              => $ruang_cd[$key],
                    'barang_id'             => $key
                );
                $this->m_pengadaan->set_detail_distribusi($params);
            }
        } else {
            // default error
            $this->tnotification->sent_notification("error", "Data gagal disimpan");
        } 
        redirect('inventarisasi/pengadaan/distribusi/' . $this->input->post('pengadaan_id'));
    }
    
    public function generate_procces() {  
        //cek data
        $this->tnotification->set_rules('pengadaan_id', 'Nomor Pengadaan', 'trim|required');  
        //proses
        if ($this->tnotification->run() !== FALSE) { 
             
            $rs_pengajuan_barang = $this->m_pengajuan_barang->get_all_barang_by_pengadaan_id($this->input->post('pengadaan_id'));
            if (!empty($rs_pengajuan_barang)) {
                $result_info = $this->m_pengadaan->get_pengadaan_by_pengadaan_id($this->input->post('pengadaan_id'));
                foreach ($rs_pengajuan_barang as $row) {
                    $lokasi_cd          = $row['lokasi_cd'];
                    $kategoribarang_cd  = $row['kategoribarang_cd'];
                    $jenisbarang_cd     = $row['jenisbarang_cd'];
                    $merk_cd            = $row['merk_cd']; 
                    $tgl                = date("dmy", strtotime($result_info['pengadaan_tgl_dist'])); 
                    $qty                = $row['pengajuanbarang_qty'];
                    $penyusutan         = $row['pengajuanbarang_penyusutan'] * 12;
                    for ($i = 1; $i <= $qty; $i++) {
                        $no_inventaris = '';
                        // jika barang generate nomor inventaris 
                        if ($row['pengajuanbarang_generate_noiventaris'] == '1' && $row['gpbarang_cd'] == '2') {
                            $no_inventaris = $lokasi_cd . "." . $kategoribarang_cd . "." . $jenisbarang_cd . "." . $merk_cd . "." . $tgl . "." . $i . "." . $qty . "." . $penyusutan;
                        }
                        
                        $params = array(
                            'barang_noinventaris'   => $no_inventaris,
                            'barang_nama'           => $row['pengajuanbarang_nama'],
                            'barang_harga_beli'     => $row['pengajuanbarang_hargasatuan'],
                            'barang_nilai_buku'     => $row['pengajuanbarang_hargasatuan'],
                            'barang_umurekonomis'   => $row['pengajuanbarang_penyusutan'],
                            'barang_keterangan'     => $row['pengajuanbarang_keterangan'],
                            'barang_kondisi'        => $row['pengajuanbarang_barang_kondisi'],
                            'barang_status'         => $row['pengajuanbarang_status'], 
                            'barang_tglbeli'        => $result_info['pengadaan_tgl_dist'], 
                            'barang_tglberakhir'    => $this->m_pengadaan->get_tgl_berakhir(array($result_info['pengadaan_tgl_dist'], $row['pengajuanbarang_penyusutan'])),
                            'barang_tglpenyusutan'  => null,
                            'barang_garansi'        => $row['pengajuanbarang_garansi'],
                            'barang_tgl_garansi'    => $row['pengajuanbarang_tgl_garansi'],
                            'barang_pengguna'       => null,
                            'barang_susut'          => $row['pengajuanbarang_susut'],
                            'gpbarang_cd'           => $row['gpbarang_cd'],
                            'vendor_cd'             => $row['vendor_cd'],
                            'lokasi_cd'             => $row['lokasi_cd'],
                            'ruang_cd'              => $row['ruang_cd'],
                            'kategoribarang_cd'     => $row['kategoribarang_cd'],
                            'jenisbarang_cd'        => $row['jenisbarang_cd'],
                            'merk_cd'               => $row['merk_cd'],
                            'pengadaan_id'          => $row['pengadaan_id'],
                            'pengajuanbarang_id'    => $row['pengajuanbarang_id'],
                            'mdb'                   => $this->com_user['user_id']
                        );
//                        print "<pre>";
//                        print_r($params);
//                        print "</pre>";
//                        exit();
                        $this->m_barang->insert($params);
                    }
                }
                
                $this->m_pengadaan->update_pengadaan_status_generate_by_pengadaan_id(array('1', $this->input->post('pengadaan_id')));
                $this->tnotification->sent_notification("success", "Nomor Inventaris  berhasil digenerate");
            }else{
                $this->tnotification->sent_notification("error", "Data Barang masih kosong");  
            }
        } else {
            // default error
            $this->tnotification->sent_notification("error", "Nomor Inventaris gagal digenerate");
        } 
        redirect('inventarisasi/pengadaan/distribusi/' . $this->input->post('pengadaan_id'));
    } 
    
    // welcome administrator
    public function generate_nomorserahterima() {  
        $pengadaan_id       = $this->input->post('pengadaan_id');
        $pengadaan_tgl_dist = $this->input->post('pengadaan_tgl_dist');
         
        $params = array(
            'pengadaan_id'          => $pengadaan_id,
            'pengadaan_tgl_dist'    => $pengadaan_tgl_dist
        );
       
        $nomor_serahterima = $this->m_pengadaan->get_nomor_serah_terima($params); 
        
        $params = array(
            $nomor_serahterima,
            $pengadaan_tgl_dist,
            $pengadaan_id
        );
        $result = $this->m_pengadaan->update_nomor_berita_serah_terima($params);
        if($result){
           echo $nomor_serahterima;
        }else{
           echo '';
        }  
    }
    
    public function cetak_nomorserahterima($pengadaan_id = "") {
        // info pengadaan
        $result_info    = $this->m_pengadaan->get_pengadaan_by_pengadaan_id($pengadaan_id); 
        // data barang pengadaan
        $detail_barang  = $this->m_pengadaan->get_all_pengajuan_barang_by_pengadaan_id($pengadaan_id);
        // data rumah tangga
        $rumah_tangga   = $this->m_bagian->get_bagian_by_id('025');
        
        $style_border  = array(
            'borders' => array(
                'allborders' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN
                )
            ) 
        );
        
        $style_bold = array(
                'font' => array(
                        'bold' => true
                )
        );
        
        $style_barang = array(
                'font' => array(
                        'name' => 'Times New Roman',
                        'size' => 10 
                )
        );
        
        //create excel
        $filepath = "resource/doc/template/berita_serah_terima.xls";
        //---
        $objReader = PHPExcel_IOFactory::createReader('Excel5');
        $this->phpexcel = $objReader->load($filepath);
        $objWorksheet = $this->phpexcel->setActiveSheetIndex(0);

        $objWorksheet->setCellValue("A2", $result_info['pengadaan_ba_dist']);
        
        $tgl_serah_terima = $this->datetimemanipulation->get_date_indonesia($result_info['pengadaan_tgl_dist']);
        $objWorksheet->setCellValue("A5", 'Pada hari ini : '.$tgl_serah_terima['hari'].', '.$tgl_serah_terima['tanggal'].' '.$tgl_serah_terima['bulan'].' '.$tgl_serah_terima['tahun'].' yang bertanda tangan dibawah ini ');
        $objWorksheet->setCellValue("B7", $result_info['bagian_name']);
        $objWorksheet->setCellValue("B8", $result_info['bagian_penanggungjawab']);
        
        $row = 13; 
        foreach ($detail_barang as $key => $result) {
            $objWorksheet->setCellValue("A".$row, ($key+1));
            $objWorksheet->setCellValue("B".$row, $result['barang_nama']);
            $objWorksheet->setCellValue("C".$row, '1');
            $objWorksheet->setCellValue("D".$row, $result['barang_noinventaris']);
            $objWorksheet->setCellValue("E".$row, $result['ruang_nomor']);
            $objWorksheet->getStyle("A" . $row.":E".$row)->applyFromArray($style_border);
            $objWorksheet->getStyle("A" . $row.":E".$row)->applyFromArray($style_barang);
            $row++;
        }
        $row++;
        
        $objWorksheet->mergeCells('A' . $row . ':E' . $row);
        $objWorksheet->setCellValue("A".$row, 'Berita acara ini dibuat untuk digunakan sebagaimana mestinya.');
        $row++;
        $row++;
        
        $objWorksheet->mergeCells('A' . $row . ':B' . $row);  
        $objWorksheet->setCellValue("A".$row, 'Bagian yang menyerahkan');
        $objWorksheet->getStyle('A'.$row.':B' . $row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objWorksheet->mergeCells('D' . $row . ':E' . $row);  
        $objWorksheet->setCellValue("D".$row, 'Bagian yang menerima');
        $objWorksheet->getStyle("D".$row.":E".$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $row++;
        
        $objWorksheet->mergeCells('A' . $row . ':B' . $row);  
        $objWorksheet->setCellValue("A".$row, 'Rumah tangga/.................');
        $objWorksheet->getStyle('A'.$row.':B' . $row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $row++;
        $row++;
        $row++;
        $row++;
        
        $objWorksheet->mergeCells('A'.$row.':B' . $row);  
        $objWorksheet->setCellValue("A".$row, $rumah_tangga['bagian_penanggungjawab']);
        $objWorksheet->getStyle('A'.$row.':B' . $row)->applyFromArray($style_bold);
        $objWorksheet->getStyle('A'.$row.':B' . $row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objWorksheet->mergeCells('D'.$row.':E'.$row);  
        $objWorksheet->setCellValue("D".$row, $result_info['bagian_penanggungjawab']);
        $objWorksheet->getStyle("D".$row.":E".$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objWorksheet->getStyle("D".$row.":E".$row)->applyFromArray($style_bold);
        
        
        $objWorksheet->mergeCells('D' . $row . ':E' . $row); 
        $file_name = str_replace("/", "_", $result_info['pengadaan_ba_dist']);
        $file_name = str_replace(".", "", $file_name);
        //--
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file_name . '.xlsx');
        header('Cache-Control: max-age=0');
        // output
        $obj_writer = PHPExcel_IOFactory::createWriter($this->phpexcel, 'Excel2007');
        $obj_writer->save('php://output');
    }
}
